package com.sx.netty.bio;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.spec.RSAOtherPrimeInfo;
import java.util.Date;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * @Author Administrator
 * @Description 传统BIO模型的演示
 * @Date 2020/11/2 13:47
 */
public class BIOServer {
    public static void main(String[] args) throws IOException {
//        创建一个线程池
        Executor threadPool = Executors.newFixedThreadPool(2);

//        创建一个ServerSocket,并绑定端口
        ServerSocket serverSocket = new ServerSocket(6666);

        System.out.println(Thread.currentThread().getName() + ":" + Thread.currentThread().getId() + "\t服务器启动...");

//        对socket进行监听
        while (true) {
//            阻塞进行等待
            System.out.println(Thread.currentThread().getName() + ":" + Thread.currentThread().getId() + "\t等待连接中...");
            Socket socket = serverSocket.accept();

            System.out.println(Thread.currentThread().getName() + ":" + Thread.currentThread().getId() + "\t连接到一个客户端请求");

//            创建一个线程用于进行通信
            threadPool.execute(() -> {

                handler(socket);

            });
        }
    }


    //    通讯方法
    public static void handler(Socket socket) {

        System.out.println(Thread.currentThread().getName() + ":" + Thread.currentThread().getId() + "\t处理当前客户端连接请求");

        byte[] bytes = new byte[1024];

        InputStream inputStream = null;
        try {
            inputStream = socket.getInputStream();
//        进行循环监听
            while (true) {
                System.out.println(Thread.currentThread().getName() + ":" + Thread.currentThread().getId() + "\t" + new Date() + "\t读取中...");
                int read = inputStream.read(bytes);
                if (read != -1) {
//                输出客户端数据
                    System.out.println(new String(bytes, 0, read));
                } else {
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
//            关闭连接
            System.out.println(Thread.currentThread().getName() + ":" + Thread.currentThread().getId() + "\t关闭与client端的连接");
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
